package fm.yichenet.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.entityEnum.CarouselScope;
import fm.entityEnum.CarouselType;
import fm.entityEnum.GoodFlagEnum;
import fm.entityEnum.ShopFlagEnum;
import fm.exception.BizException;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongoService.UserService;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.ArticleService;
import fm.yichenet.mongo.service.CarouselService;
import fm.yichenet.mongo.service.GoodMgrService;
import fm.yichenet.mongo.service.ShopMgrService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by CM on 17/5/26.
 */
@Controller
@RequestMapping("/portal")
public class PortalController extends BaseController {


    @Autowired
    private GoodMgrService goodMgrService;
    @Autowired
    private ShopMgrService shopMgrService;
    @Autowired
    private CarouselService carouselService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    /**
     * 平台首页标记商品获取
     *
     * @param flag
     * @return
     */
    @ResponseBody
    @RequestMapping("/good/flag/list/{flag}")
    public Map getGoodList(@PathVariable GoodFlagEnum flag, String city,String shop_id) {
        Map res = new HashMap();
        try {
            MCondition mc = MCondition.create(MRel.and);
            mc.append("flags.name", flag.toString());
            if(StringUtils.isNotEmpty(shop_id)){
                mc.append("shop_id", shop_id);
            }
            if (StringUtils.isEmpty(city) == false) {
                mc.append("flags.city", city);
            }
            mc.append("status", "1");
            List<DBObject> goods = goodMgrService.getList(mc.toDBObject().toMap(), null, null, null);


            if (StringUtils.isNotEmpty(city)) {
                if (CollectionUtils.isEmpty(goods)) {
                    MCondition defaultCondition = MCondition.create(MRel.and);
                    defaultCondition.append("flags.name", flag.toString());
                    defaultCondition.append("flags.city", "default");
                    defaultCondition.append("status", 1 + "");
                    if(StringUtils.isNotEmpty(shop_id)){
                        defaultCondition.append("shop_id", shop_id);
                    }
                    goods = goodMgrService.getList(defaultCondition.toDBObject().toMap(), null, null, null);

                }
            }


            res.put("data", goods);
            LOGGER.info("{} result:{}", flag.getDesc(), goods.size());
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/shop/flag/list")
    public Map getShopList(ShopFlagEnum pageType, String city) {
        Map res = new HashMap();
        try {
            List<DBObject> flagShops = shopMgrService.getFlagShop(pageType.toString(), city);
            res.put("data", flagShops);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/carousel/list/{scope}")
    public Map getCarouselScopeList(@PathVariable CarouselScope scope, String shopId, String city, String loc, Long sectionId) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(city)) {
                city = "default";
            }
            List<DBObject> object = carouselService.getList(null, scope, city, shopId, new Date(), sectionId);
            if (CollectionUtils.isEmpty(object)) {
                object = carouselService.getList(null, scope, "default", shopId, new Date(), sectionId);
            }
            res.put("data", object);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/info/list")
    public Map getInfoArticleList(String city, String pagetype, Long sectionId) {
        Map res = new HashMap();
        try {
            DBObject condition = new BasicDBObject();
            condition.put("flags.name", pagetype);
            if (sectionId != null) {
                condition.put("sectionId", sectionId);
            }
            List<DBObject> infos = articleService.getInfoArticleList(condition);
            for (DBObject info : infos) {
                List<Map<String, String>> flags = (List<Map<String, String>>) info.get("flags");
                List<Map<String, String>> newflags = new ArrayList<>();
                for (Map flag : flags) {
                    if (flag.get("name").toString().equals(pagetype)) {
                        newflags.add(flag);
                    } else {
                        continue;
                    }
                }
                info.put("flags", newflags);
            }
            res.put("data", infos);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    /**
     * 首页新品推荐配置获取
     *
     * @param city
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping("/newgoodinfo/list")
    public Map getNewGoodSetInfo(String city, CarouselType type) {
        Map res = new HashMap();
        if (StringUtils.isEmpty(city)) {
            city = "default";
        }
        try {
            List<DBObject> infos = goodMgrService.getNewGoodSet(city, type);
            res.put("data", infos);
            this.success(res);
        } catch (Exception e) {
            LOGGER.error("occur un-expected error", e);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    /**
     * 新品推荐信息修改
     *
     * @param id
     * @param userId
     * @param goodId
     * @param img
     * @return
     */
    @ResponseBody
    @RequestMapping("/newgoodinfo/update")
    public Map updateNewGoodSetInfo(String id, String userId, String goodId, String img, String userName, String goodName) {
        LOGGER.info("id:{} userID:{} goodID:{}", id, userId, goodId);
        Map res = new HashMap();
        Map param = new HashMap();
        param.put("_id", id);
        Map updateItem = new HashMap();
        if (StringUtils.isNotEmpty(userId)) {
            updateItem.put("userId", userId);
        }
        if (StringUtils.isNotEmpty(goodId)) {
            updateItem.put("goodID", goodId);
        }
        if (StringUtils.isNotEmpty(img)) {
            updateItem.put("img", img);
        }
        if (StringUtils.isNotEmpty(userName)) {
            updateItem.put("userName", userName);
        }
        if (StringUtils.isNotEmpty(goodName)) {
            updateItem.put("goodName", goodName);
        }

        try {
            int count = goodMgrService.updateNewGoodSet(param, updateItem);
            res.put("data", count);
            this.success(res);
        } catch (Exception e) {
            LOGGER.error("occur un-expected error", e);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    /**
     * 根据配置获取商品信息
     *
     * @param city
     * @return
     */
    @ResponseBody
    @RequestMapping("/adviegood/list")
    public Map getAdviceGooodInfo(String city) {
        Map res = new HashMap();
        if (StringUtils.isNotEmpty(city)) {
            city = "default";
        }
        try {
            List goodsinfo = null;
            List<DBObject> infos = goodMgrService.getNewGoodSet(city, CarouselType.GOOD);
            for (DBObject info : infos) {
                Map param = new HashMap();
                param.put("good_id", info.get("good_id"));
                List<DBObject> good = (List<DBObject>) goodMgrService.getGood(param);
                if (good == null) {
                    LOGGER.error("根据配置未找到对应商品:" + info.get("good_id"));
                }
                goodsinfo.add(good);
            }
            res.put("data", goodsinfo);
            this.success(res);
        } catch (Exception e) {
            LOGGER.error("occur un-expected error", e);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    /**
     * 登记平台入驻人联系信息
     */
     @ResponseBody
        @RequestMapping(value = "/applay/info",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
        public Map InsertApplayInfo (String name ,String phone){
            Map res = new HashMap();
            try{
               userService.InserApplayInfo(name,phone);
                res.put("data","");
                this.success(res);
            }catch (BizException ex){
                LOGGER.error("发生错误:",ex);
                this.failed(res,ex.getMessage());
            }catch (Exception ex){
                LOGGER.error("发生异常",ex);
                this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
            }
         return res;
     }
    /**
     *获取平台申请列表
     */
        @ResponseBody
        @RequestMapping(value = "/applay/list",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
        public Map getApplayList(Integer pageNum,Integer pageSize){
            Map res = new HashMap();
            try{
                List<DBObject> list = userService.getApplayList(pageNum,pageSize);
                res.put("data",list);
                this.success(res);
            }catch (BizException ex){
                LOGGER.error("发生错误:",ex);
                this.failed(res,ex.getMessage());
            }catch (Exception ex){
                LOGGER.error("发生异常",ex);
                this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
            }
            return res;
        }

    /**
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/applay/delete",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public Map deleteApplayInfo (String phone){
        Map res = new HashMap();
        try{
            userService.deleteApplayInfo(phone);
            res.put("data","");
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("发生错误:",ex);
            this.failed(res,ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("发生异常",ex);
            this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }

    /**
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/applay/update",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public Map updateApplayInfo (String phone){
        Map res = new HashMap();
        try{
            userService.updateApplayInfo(phone);
            res.put("data","");
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("发生错误:",ex);
            this.failed(res,ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("发生异常",ex);
            this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }
}
